import * as React from "react";
import { cloneDeep } from "lodash";
import { Spin, Table, Space, Typography, Modal, Button } from "antd";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import { PlusOutlined } from "@ant-design/icons";
import IconFont from "../../../../../../assets/ICON";
import { VirtualDeviceConditionState } from "../VirtualDeviceCondition";
import { Devicedelete, getDeviceManagement } from "../../../deviceseversapi";
import { arrRemoveItem } from "../../../../../../utils/common";
import "./index.less";
import moment from "moment";
import VirtualDeviceAddModal from "../VirtualDeviceAddModal";
import BindDeviceModal from "../BindDeviceModal";
const { Text } = Typography;
export interface VirtualDeviceTableProps {
  query: VirtualDeviceConditionState;
  subItem: any[];
}

export interface VirtualDeviceTableState {
  loading: boolean;
  pageSize: number;
  pageIndex: number;
  total: number;
  devVal: string;
  energyType: string;
  typeId: string;
  selectedRowKeys: string[];
  addVisible: boolean; //新增/编辑虚拟设备
  addSeleVisible: boolean; //添加可选真实设备池
  bindVisible: boolean; //绑定公式操作
  preBindingTable: any[]; //与绑定设备
  initValue: any;
  subItem: any[];
}

class VirtualDeviceTable extends React.Component<
  VirtualDeviceTableProps,
  VirtualDeviceTableState
> {
  state = {
    loading: false,
    pageSize: 20,
    pageIndex: 1,
    total: 0,
    devVal: "",
    energyType: "",
    typeId: "",
    selectedRowKeys: [],
    addVisible: false,
    addSeleVisible: false,
    bindVisible: false,
    preBindingTable: [],
    initValue: null,
    subItem: [],
  };
  private dataSouce: any[] = [];
  private columns: columnsDataCLass[] = [
    {
      key: "no",
      title: "设备编号",
      dataIndex: "no",
      width: 100,
    },
    {
      key: "energyType",
      title: "能源类型",
      dataIndex: "energyType",
      width: 100,
      render: (text, record, index) => {
        let str = "";
        if (record.energyType === "1") {
          str = "电";
        } else if (record.energyType === "2") {
          str = "水";
        } else if (record.energyType === "3") {
          str = "原煤";
        } else if (record.energyType === "4") {
          str = "原油";
        } else if (record.energyType === "5") {
          str = "天然气";
        } else if (record.energyType === "6") {
          str = "蒸气";
        } else {
          str = "";
        }
        return str;
      },
    },
    {
      key: "name",
      title: "设备名称",
      dataIndex: "name",
      width: 100,
    },
    {
      key: "formula",
      title: "公式",
      dataIndex: "formula",
      width: 100,
    },
    {
      key: "createTime",
      title: "创建时间",
      dataIndex: "createTime",
      width: 100,
      render: (text: string) => {
        return moment(text).format("YYYY-MM-DD");
      },
    },
    {
      title: "操作",
      key: "action",
      dataIndex: "action",
      width: 200,
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.onBindSeleDevice(record);
                }}
              >
                <IconFont type="icon_bangding" style={{ color: "#7B9AFC" }} />
                <Text>绑定</Text>
              </span>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.onDeleteItem(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  /**钩子函数 */
  componentWillMount() {
    this.getDataSouce();
  }

  shouldComponentUpdate(
    newProps: VirtualDeviceTableProps,
    newState: VirtualDeviceTableState
  ) {
    if (newProps.query !== this.props.query) {
      this.setState({
        devVal: newProps.query.devVal,
        energyType: newProps.query.energyType,
        typeId: newProps.query.typeId,
      });
      this.getDataSouce();
    }
    if (newProps.subItem !== this.props.subItem) {
      this.setState({ subItem: newProps.subItem });
    }
    return true;
  }
  /**操作 */
  //绑定前选择真实设备
  onBindSeleDevice(record) {
    this.setState({ initValue: record, bindVisible: true });
  }
  //编辑
  onEdit(record) {
    this.setState({ initValue: record, addVisible: true });
  }
  //批量删除
  onDelete() {
    let pream: any = {
      idList: this.state.selectedRowKeys,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除设备",
      onOk: () => {
        _this.delete(pream);
      },
    });
  }
  //单项删除
  onDeleteItem(record: any) {
    let pream: any = {
      idList: [record.id],
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除该设备",
      onOk: () => {
        _this.delete(pream);
      },
    });
    //
  }
  /**数据请求 */
  //请求虚拟设备数据源
  async getDataSouce() {
    let { pageIndex, pageSize, devVal, energyType, typeId } = this.state;
    let pream = {
      pageIndex,
      pageSize,
      queryData: {
        devVal,
        energyType,
        isFictitious: "1",
        typeId,
      },
    };
    try {
      this.setState({ loading: true });
      let res: any = await getDeviceManagement(pream);
      const json: AjaxData = res;
      if (json.success) {
        this.dataSouce = json.data.records.map((item) => {
          item.key = item.id;
          return item;
        });
        this.setState({ loading: false });
        this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            this.setState({ loading: false });
          },
        });
      }
    } catch (error) {}
  }
  //删除设备
  async delete(pream) {
    try {
      let res: any = await Devicedelete(pream);
      let json: AjaxData = res;
      if (json.success) {
        this.getDataSouce();
      } else {
        Modal.error({ title: json.message });
      }
    } catch (error) {}
  }
  //选中的虚拟设备
  onSelectChange = (record, selected) => {
    let seleArr: any = cloneDeep(this.state.selectedRowKeys);

    if (selected) {
      //选中
      seleArr.push(record.id);
    } else {
      //取消
      seleArr = arrRemoveItem(record.id, seleArr);
    }
    this.setState({ selectedRowKeys: seleArr });
  };
  //全选虚拟设备
  onSelectAll = (selected, selectedRows, changeRows) => {
    let seleArr: any = cloneDeep(this.state.selectedRowKeys);

    if (selected) {
      changeRows.map((item) => {
        seleArr.push(item.id);
        seleArr = Array.from(new Set(seleArr));
        return item;
      });
    } else {
      changeRows.map((item) => {
        seleArr = arrRemoveItem(item.id, seleArr);
        return item;
      });
    }
    this.setState({ selectedRowKeys: seleArr });
  };
  //
  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onSelect: this.onSelectChange,
      onSelectAll: this.onSelectAll,
    };
    return (
      <div className="VirtualDeviceTable rowcon_body">
        <div className="operation">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              this.setState({ addVisible: true });
              // console.log();
            }}
          >
            新增
          </Button>

          <Button
            type="primary"
            icon={<IconFont type="icon_form_shanchu" />}
            danger
            onClick={() => {
              this.onDelete();
            }}
          >
            删除
          </Button>
        </div>
        <Spin spinning={this.state.loading}>
          <Table
            columns={this.columns}
            dataSource={this.dataSouce}
            rowSelection={{
              ...rowSelection,
            }}
            pagination={{
              pageSize: this.state.pageSize,
              total: this.state.total,
              current: this.state.pageIndex,
              onChange: (page: number) => {
                this.setState({ pageIndex: page });
                this.getDataSouce();
              },
            }}
          ></Table>
        </Spin>
        <VirtualDeviceAddModal
          visible={this.state.addVisible}
          subItem={this.state.subItem}
          onOk={() => {
            this.setState({ addVisible: false, initValue: null });
            this.getDataSouce();
          }}
          onCancel={() => {
            this.setState({ addVisible: false, initValue: null });
          }}
          defaultValue={this.state.initValue}
        />

        <BindDeviceModal
          visible={this.state.bindVisible}
          record={this.state.initValue}
          onOk={() => {
            this.setState({ bindVisible: false, initValue: null });
          }}
          onCancel={() => {
            this.setState({ bindVisible: false, initValue: null });
          }}
        />
      </div>
    );
  }
}

export default VirtualDeviceTable;
